﻿using System;
using Common.Dao;
using Common.Model;
using Common.util;
using Newtonsoft.Json;

namespace Common.Redis
{
    public class NewsRedisDbProvider
    {
        private static readonly String NewsLastUpdateTime = "news:lastUpdateTime:";
        private static readonly String AnswderLastUpdateTime = "answer:lastUpdateTime:";
        private static readonly String QuestionLastUpdateTime = "question:lastUpdateTime:";

        public static DateTime GetLastNewsDateTime(string @from)
        {
            String key = NewsLastUpdateTime + from ;
            String result = RedisUtils.HtRedis.GetDatabase().StringGet(key);
            DateTime lastSiteTime;
            if (String.IsNullOrEmpty(result))
            {
                News news = NewsDao.GetLastNews(from);
                if (news != null)
                {
                    lastSiteTime = news.SiteTime;
                }
                else
                {
                    lastSiteTime = DateTime.Now.AddDays(-1);
                }
            }
            else
            {
                lastSiteTime = JsonConvert.DeserializeObject<DateTime>(result);
            }

            return lastSiteTime;
        }

        public static void SetLastNewsDatetime(string @from, DateTime lastNewsDateTime)
        {
            String key = NewsLastUpdateTime + from;
            RedisUtils.HtRedis.GetDatabase().StringSet(key, JsonConvert.SerializeObject(lastNewsDateTime),new TimeSpan(5,0,0));
        }

        public static void SetLastQuestionDatetime(DateTime lastNewsDateTime)
        {
            String key = QuestionLastUpdateTime;
            RedisUtils.HtRedis.GetDatabase().StringSet(key, JsonConvert.SerializeObject(lastNewsDateTime), new TimeSpan(5, 0, 0));
        }

        public static void SetLastAnswerDatetime(DateTime lastNewsDateTime)
        {
            String key = AnswderLastUpdateTime;
            RedisUtils.HtRedis.GetDatabase().StringSet(key, JsonConvert.SerializeObject(lastNewsDateTime), new TimeSpan(5, 0, 0));
        }
    }
}